<template>
  <div class="app-container" ref="appContainer">
    <PropTable
      ref="tableData"
      :loading="loading"
      :columns="column"
      :data="data"
      @reset="reset"
      @onSubmit="onSubmit"
      @add="add"
    >
      <template v-slot:operation="scope">
        <el-button
          type="success"
          size="small"
          icon="CircleCheck"
          v-if="!scope.row.pigeonhole"
          @click="complete(scope.row, true)"
        >
          完成归档
        </el-button>
        <el-button
          type="danger"
          size="small"
          icon="CircleClose"
          v-if="scope.row.pigeonhole"
          @click="complete(scope.row, false)"
        >
          取消归档
        </el-button>
        <el-button type="primary" size="small" icon="Plus" @click="addParticipants(scope.row)">
          添加人员
        </el-button>
        <el-button type="primary" size="small" icon="Edit" @click="edit(scope.row)">
          编辑
        </el-button>
        <!--  <el-button @click="del(scope.row)" type="danger" size="small" icon="Delete">
          删除
        </el-button>-->
      </template>
    </PropTable>

    <el-drawer v-model="dialogVisible" title="编辑">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
      >
        <el-form-item label="项目名称：" prop="projectName">
          <el-input v-model="ruleForm.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目简称：" prop="projectBrief">
          <el-input v-model="ruleForm.projectBrief" placeholder="请输入项目简称" />
        </el-form-item>
        <el-form-item label="项目类型：" prop="projectType">
          <el-select
            v-model="ruleForm.projectType"
            placeholder="请选择项目类型"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="ite in projectTypeList"
              :key="ite.value"
              :label="ite.label"
              :value="ite.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称：" prop="clientId">
          <el-select
            v-model="ruleForm.clientId"
            placeholder="请选择客户名称"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="ite in clientList"
              :key="ite.id"
              :label="ite.clientName"
              :value="ite.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人：" prop="chargeNickname">
          <el-select
            v-model="ruleForm.chargeNickname"
            placeholder="请选择负责人"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="ite in userList"
              :key="ite.nickname"
              :label="`${ite.nickname}[${ite.department}]${ite.title}`"
              :value="ite.nickname"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleClose(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-drawer>
    <el-drawer v-model="dialogVisible2" title="新增">
      <el-form
        ref="ruleFormRef2"
        :model="newProject"
        :rules="rules2"
        label-width="120px"
        class="demo-ruleForm2"
        :size="formSize"
      >
        <el-form-item label="项目名称：" prop="projectName">
          <el-input v-model="newProject.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目简称：" prop="projectBrief">
          <el-input v-model="newProject.projectBrief" placeholder="请输入项目简称" />
        </el-form-item>
        <el-form-item label="项目类型：" prop="projectType">
          <el-select
            v-model="newProject.projectType"
            placeholder="请选择项目类型"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="ite in projectTypeList"
              :key="ite.value"
              :label="ite.label"
              :value="ite.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称：" prop="clientId">
          <el-select
            v-model="newProject.clientId"
            placeholder="请选择客户名称"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="ite in clientList"
              :key="ite.id"
              :label="ite.clientName"
              :value="ite.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人：" prop="chargeNickname">
          <el-select
            v-model="newProject.chargeNickname"
            placeholder="请选择负责人"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="ite in userList"
              :key="ite.nickname"
              :label="`${ite.nickname}[${ite.department}]${ite.title}`"
              :value="ite.nickname"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="addProject(ruleFormRef2)">确定</el-button>
        </span>
      </template>
    </el-drawer>
    <ParticipantsDrawer ref="participantsDrawer" />
  </div>
</template>
<script lang="ts" setup name="comprehensive">
  import { ref, reactive, onMounted, nextTick } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import ParticipantsDrawer from './components/participantsDrawer.vue'
  import {
    postProjectSearch,
    putProject,
    deleteProjectById,
    postProject,
  } from '@/api/controller/project-controller/index'
  import { postSysUserMatch } from '@/api/controller/sys-user-controller/index'
  import { getSysProTypeList } from '@/api/controller/sys-user-controller/index'
  import { postClientMatch } from '@/api/controller/client-controller/index'
  const loading = ref(true)
  const appContainer = ref(null)
  import PropTable from '@/components/Table/PropTable/index.vue'

  const column = [
    { name: 'projectNumber', label: '项目编号', inSearch: true, valueType: 'input', width: 140 },
    { name: 'projectBrief', label: '项目简称', inSearch: true, valueType: 'input', width: 200 },
    { name: 'projectType', label: '项目类型', inSearch: true, valueType: 'input', width: 160 },
    { name: 'projectStatus', label: '项目状态', valueType: 'input', width: 120 },
    { name: 'clientName', label: '客户名称', valueType: 'input', width: 240 },
    { name: 'chargeNickname', label: '负责人', valueType: 'input', width: 100 },
    {
      name: 'projectStartTime',
      label: '创建时间',
      sorter: true,
      valueType: 'input',
      width: 130,
    },
    { name: 'operation', slot: true, fixed: 'right', width: 300, label: '操作' },
  ]
  const data = ref(null)

  const formSize = ref('default')
  const ruleFormRef = ref<FormInstance>()
  const ruleFormRef2 = ref<FormInstance>()
  const ruleForm = ref({
    projectName: null,
    projectBrief: null,
    projectType: null,
    projectStatus: null,
    clientId: null,
    chargeNickname: null,
    projectStartTime: null,
    projectEndTime: null,
    remark: null,
  })

  const rules = reactive({
    projectName: [
      { required: true, message: '请输入项目名称', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    projectBrief: [
      { required: true, message: '请输入项目简称', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    projectType: [
      { required: true, message: '请输入项目类型', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    chargeNickname: [{ required: true, message: '请选择负责人', trigger: 'blur' }],
    clientId: [{ required: true, message: '请选择客户名称', trigger: 'blur' }],
  })

  const rules2 = reactive({
    projectName: [
      { required: true, message: '请输入项目名称', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    projectBrief: [
      { required: true, message: '请输入项目简称', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    projectType: [
      { required: true, message: '请输入项目类型', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    clientId: [{ required: true, message: '请选择客户名称', trigger: 'blur' }],
    chargeNickname: [{ required: true, message: '请选择负责人姓名', trigger: 'blur' }],
  })
  const dialogVisible = ref(false)
  const dialogVisible2 = ref(false)
  const tableData = ref(null)
  //修改
  const handleClose = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        const result = await putProject(ruleForm.value, { loading: true })
        if (result.code === 200) {
          try {
            loading.value = true
            const result = await postProjectSearch(tableData.value?.formInline)
            data.value = result.data
            dialogVisible.value = false
            ElMessage.success('修改成功')
          } finally {
            loading.value = false
          }
        }
      } else {
        ElMessage.warning('请正确填写表单')
        return false
      }
    })
  }
  // 打开新增弹窗
  const newProject = ref({
    projectName: null,
    projectBrief: null,
    projectType: null,
    clientId: null,
    chargeNickname: null,
  })
  const add = () => {
    newProject.value = {
      projectName: null,
      projectBrief: null,
      projectType: null,
      clientId: null,
      chargeNickname: null,
    }
    dialogVisible2.value = true
    nextTick(() => {
      ruleFormRef2.value.clearValidate()
    })
  }

  //新增一个项目
  const addProject = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        const result = await postProject(newProject.value, { loading: true })
        if (result.code === 200) {
          try {
            loading.value = true
            const result = await postProjectSearch(tableData.value?.formInline)
            data.value = result.data
            dialogVisible2.value = false
            ElMessage.success('添加成功')
          } finally {
            loading.value = false
          }
        }
      } else {
        ElMessage.warning('请正确填写表单')
        return false
      }
    })
  }

  //打开编辑弹窗
  const edit = (row) => {
    ruleForm.value = { ...row }
    dialogVisible.value = true
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }
  // 删除当前项
  const del = async (row) => {
    ElMessageBox.confirm('你确定要删除当前项吗?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    })
      .then(async () => {
        const result = await deleteProjectById({ id: row.id })
        if (result.code === 200) {
          try {
            loading.value = true
            const result = await postProjectSearch(tableData.value?.formInline)
            data.value = result.data
            dialogVisible.value = false
            ElMessage.success('删除成功')
          } finally {
            loading.value = false
          }
        }
      })
      .catch(() => {
        console.log('错误')
      })
  }
  //重置搜索条件
  const reset = async () => {
    try {
      loading.value = true
      let pageInfo = {
        pageNum: 1,
        pageSize: 15,
      }
      const result = await postProjectSearch(pageInfo)
      data.value = result.data
    } finally {
      loading.value = false
    }
  }
  //搜索
  const onSubmit = async (val) => {
    try {
      loading.value = true
      let result = await postProjectSearch(val)
      data.value = result.data
    } finally {
      loading.value = false
    }
  }

  //添加参与人员抽屉
  const participantsDrawer = ref()
  const addParticipants = (data) => {
    participantsDrawer.value.show(data)
  }

  const userList = ref([])
  const clientList = ref([])
  const projectTypeList = ref([])
  //初始化
  onMounted(async () => {
    try {
      loading.value = true
      let pageInfo = {
        pageNum: 1,
        pageSize: 15,
      }
      postSysUserMatch({}).then((res) => {
        userList.value = res.data
      })
      postClientMatch({}).then((res) => {
        clientList.value = res.data
      })
      getSysProTypeList().then((res) => {
        projectTypeList.value = res.data
      })
      const result = await postProjectSearch(pageInfo)
      data.value = result.data
    } finally {
      loading.value = false
    }
  })

  const complete = (row, type) => {
    ElMessageBox.confirm(type ? '你确定要归档当前项吗?' : '你确定要取消归档当前项吗?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    }).then(async () => {
      const result = await putProject({ id: row.id, pigeonhole: type }, { loading: true })
      if (result.code === 200) {
        try {
          loading.value = true
          const result = await postProjectSearch(tableData.value?.formInline)
          data.value = result.data
          ElMessage.success(type ? '归档成功' : '取消归档')
        } finally {
          loading.value = false
        }
      }
    })
  }
</script>

<style scoped>
  .edit-input {
    padding-right: 100px;
  }
  .app-container {
    flex: 1;
    display: flex;
    width: 100%;
    padding: 16px;
    box-sizing: border-box;
  }
  .cancel-btn {
    position: absolute;
    right: 15px;
    top: 10px;
  }
</style>
